﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using EmailCenter_SEK53.Models;
using System.Text.RegularExpressions;
using System.IO;
using System.Net;
using System.Net.Mail;
using EmailCenter_SEK53.Views;
using NHunspell;
using Utilities;

namespace EmailCenter_SEK53
{
    public partial class frmMain : DevComponents.DotNetBar.Office2007RibbonForm
    {
        public IRepository _repository;
        public bool bAlertShowed = false;
        private static int currentUserAccountId = 1;

        //public frmMain() : this(new Repository()) { }

        public frmMain(IRepository repository)
        {
            _repository = repository;
        }

        private static IList<Models.Email> emailList;

        public frmMain()
            : this(new Repository())
        {
            InitializeComponent();
            try
            {
                ShowEmailList(1, 1);
            }
            catch (Exception e) { }

            lstEmail.SelectedIndexChanged += new EventHandler(lstEmail_SelectedIndexChanged);
        }

        void lstEmail_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (lstEmail.SelectedItems.Count > 0)
            {
                int index = lstEmail.SelectedItems[0].Index;
                //MessageBox.Show(index.ToString());
                string selectedEmailContent = emailList.ElementAt(index).contents;
                wbEmailContent.DocumentText = String.Format("<html><head><body><p>{0}</p></body></head></html>", selectedEmailContent);
            }
        }

        bool SendEmailExampleCode()
        {
            MailAddress mailfrom = new MailAddress("sender@gmail.com");
            MailAddress mailto = new MailAddress("ncc1990@gmail.com");
            MailMessage newmsg = new MailMessage(mailfrom, mailto);

            newmsg.Subject = "Chào";
            newmsg.Body = "Xin chào bạn";

            //For File Attachment, more file can also be attached

            Attachment att = new Attachment("e:\\image.jpg");
            newmsg.Attachments.Add(att);

            SmtpClient smtp = new SmtpClient("smtp.gmail.com", 587);
            smtp.UseDefaultCredentials = false;
            smtp.Credentials = new NetworkCredential("20080320@student.hut.edu.vn", "pass");
            smtp.EnableSsl = true;
            smtp.Send(newmsg);
            return true;
        }

        private void btnNewEmail_Click(object sender, EventArgs e)
        {
            frmSendEmail frmSendEmail = new frmSendEmail();
            frmSendEmail.ShowDialog();
        }

        EmailParser ParseEmail(string filepath)
        {
            string emailText = File.ReadAllText(filepath);
            return new EmailParser(emailText);
        }

        int DownloadAllEmail(Pop3Client client)
        {
            int n = client.GetEmailCount();
            string s;
            for (int i = 1; i <= n; i++)
            {
                DateTime now = DateTime.Now;
                string name = now.Year.ToString("D4") + now.Month.ToString("D2") +
                            now.Day.ToString("D2") + now.Hour.ToString("D2") +
                            now.Minute.ToString("D2") + now.Second.ToString("D2") +
                            now.Millisecond.ToString("D3");

                s = client.GetEmailText(i);
                StreamWriter myfile = File.CreateText(name + ".email");
                myfile.Write(s);
                myfile.Close();

                EmailParser emailparser = new EmailParser(s);
                //  Add email to database
                //  emailparser.From;
                //  emailparser.To;
                //  emailparser.Subject;
                //  emailparser.content;
            }
            return n;
        }

        public EmailAccount account = null;

        string inipath = Application.StartupPath + "\\config.ini" ;//@"E:\config.ini";
        //string Host = "pop.gmail.com";
        //int Port = 995;
        //string username = "ncc1990@gmail.com";
        //string pass = "#";
        //bool IsSecure = true;

        bool AutoLogin = false;

        void LoadConfig()
        {
            IniFile inifile = new IniFile(inipath);
            account.Host = inifile.IniReadValue("EmailCenter", "Host");
            account.Port = (int)inifile.IniReadInt("EmailCenter", "Port", 0);
            account.Email = inifile.IniReadValue("EmailCenter", "Email");
            account.Password = inifile.IniReadValue("EmailCenter", "Password");
            try
            {
                account.Password = DESCrypto.Decrypt(account.Password);
            }
            catch (Exception ex)
            {
                account.Password = "";
            }

            if (inifile.IniReadInt("EmailCenter", "Secure", 0) == 0)
                account.IsSecure = false;
            else
                account.IsSecure = true;

            if (inifile.IniReadInt("EmailCenter", "AutoLogin", 0) == 0)
                AutoLogin = false;
            else
                AutoLogin = true;
        }

        void SaveConfig()
        {
            IniFile inifile = new IniFile(inipath);
            inifile.IniWriteValue("EmailCenter", "Host", account.Host);
            inifile.IniWriteValue("EmailCenter", "Port", account.Port.ToString());
            inifile.IniWriteValue("EmailCenter", "Email", account.Email);
            inifile.IniWriteValue("EmailCenter", "Password",
                DESCrypto.Encrypt(account.Password));

            int i;
            if (account.IsSecure)
                i = 1;
            else
                i = 0;
            inifile.IniWriteValue("EmailCenter", "Secure", i.ToString());

            if (AutoLogin)
                i = 1;
            else
                i = 0;
            inifile.IniWriteValue("EmailCenter", "AutoLogin", i.ToString());
        }

        //  Dinh ky check mail, tai ve va phan tich
        private void timerCheckEmail_Tick(object sender, EventArgs e)
        {
            //timerCheckEmail.Enabled = false;
            if (account == null)
            {
                account = new EmailAccount();
            }

            if (bAlertShowed)
                return;

            if (account.Status == EmailAccount.NOTCONNECTED)
            {
                if (DoLogin(account) == false)
                    return;
            }

            
            int n = account.GetNewEmailsCount();
            //string s;
            account.Close();

            if (n > 0)
            {
                Alert m_AlertOnLoad = new Alert(this);
                Rectangle r = Screen.GetWorkingArea(this);
                m_AlertOnLoad.Location = new Point(r.Right - m_AlertOnLoad.Width, r.Bottom - m_AlertOnLoad.Height);
                m_AlertOnLoad.AutoClose = false;
                m_AlertOnLoad.AutoCloseTimeOut = 0;
                m_AlertOnLoad.AlertAnimation = DevComponents.DotNetBar.eAlertAnimation.BottomToTop;
                m_AlertOnLoad.AlertAnimationDuration = 300;
                m_AlertOnLoad.Show(false);
                bAlertShowed = true;
            }

        }

        private void ndInbox_NodeClick(object sender, EventArgs e)
        {
            ShowEmailList(account.Id, 1);
        }

        public void OnClickAlertSubject()
        {
            //ndInbox.SetSelectedCell(DevComponents.AdvTree.Cell.
            ShowEmailList(account.Id, 1);
        }


        void ShowEmailList(int accountid, int emailtype)
        {
            //lstEmail.Clear();
            emailList = (IList<Models.Email>)_repository.GetEmailList(emailtype, accountid);
            lstEmail.Items.Clear();
            foreach (Models.Email e in emailList)
            {
                //chkLstBxEmail.Items.Add(String.Format("From:{0}             Subject:{1}", e.partnerName, e.subject));
                ListViewItem lvi = new ListViewItem(new string[] { e.partnerName, e.subject });
                lstEmail.Items.Add(lvi);
            }
        }

        private void frmMain_Load(object sender, EventArgs e)
        {
            account = new EmailAccount();
            timerCheckEmail.Enabled = false;
            if (DoLogin(account))
            {
                int id = _repository.isAccountExist(account.Email);
                if (id >= 0)
                {
                    List<EmailParser> listEmail = account.DownloadAndParseAll(Application.StartupPath + "\\Email");
                    foreach (EmailParser email in listEmail)
                    {
                        _repository.InsertNewEmail(1, email.From,
                            email.PartnerName,
                            email.Subject,
                            email.UtcDateTime.ToString(),
                            email.content, id);

                    }
                    this.OnClickAlertSubject();
                    account.Close();
                    timerCheckEmail.Enabled = true;
                }
            }
        }

        bool bLoginShow = false;
        bool DoLogin(EmailAccount account)
        {
            if (bLoginShow)
                return false;

            this.LoadConfig();
            //account.Host = Host;
            //account.Port = Port;
            //account.Email = username;
            //account.Password = pass;
            //account.IsSecure = true;

            bool bConnectOk = false;
            Login login = new Login();
            do
            {
                if (AutoLogin == false)
                {
                    login.Host = account.Host;
                    login.Port = account.Port;
                    login.Email = account.Email;
                    login.Password = account.Password;
                    login.IsSecure = account.IsSecure;
                    login.AutoLogin = AutoLogin;
                    bLoginShow = true;
                    if (login.ShowDialog() == DialogResult.OK)
                    {
                        account.Host = login.Host;
                        account.Port = login.Port;
                        account.Email = login.Email;
                        account.Password = login.Password;
                        account.IsSecure = login.IsSecure;
                        AutoLogin = login.AutoLogin;
                    }
                    else
                    {
                        timerCheckEmail.Enabled = false;
                        return false;
                    }

                    bLoginShow = false;
                }

                try
                {
                    account.Connect();
                    bConnectOk = true;
                    this.SaveConfig();
                }
                catch (Exception ex)
                {
                    account.Close();
                }
            } while (bConnectOk == false);

            if (bConnectOk)
            {
                account.Id = _repository.isAccountExist(account.Email);
                if (account.Id < 0)
                    account.Id = _repository.InsertNewAccount(account.Email, account.Email, "");
            }

            currentUserAccountId = account.Id;
            ShowEmailList(currentUserAccountId, 1);
            return bConnectOk;
        }

        private void facebook_NodeClick(object sender, EventArgs e)
        {
            ShowEmailList(currentUserAccountId, 2);
        }

        private void spam_NodeClick(object sender, EventArgs e)
        {
            ShowEmailList(currentUserAccountId, 3);
        }
    }
}
